/*
 * The MIT License
 * Copyright (c) 2012 kc4.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.kc4.sso.auth.section.provider;

import java.io.Serializable;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.kc4.sso.auth.SSOContextParameters;
import org.kc4.sso.auth.SSOProviderInitParameters;
import org.kc4.sso.auth.section.InterruptedSectionException;
import org.kc4.sso.auth.section.ModelSection;
import org.kc4.sso.crypto.SSOAsymmetricCipher;
import org.kc4.sso.crypto.SSOSymmetricCipher;
import org.kc4.sso.filter.SSOProviderFilter.EnduserSignonSequence;
import org.kc4.sso.session.SSOSession;
import org.kc4.sso.session.SSOSessionStore;
import org.kc4.util.NamedValuesUriBuilder;

/**
 * @author yoichi kikuchi
 *
 */
public class SucceededSignonOnInvalidSessionSection extends ModelSection {

	/**
	 * インスタンスを生成します。
	 *
	 * @param request リクエスト。
	 * @param response レスポンス。
	 */
	public SucceededSignonOnInvalidSessionSection(HttpServletRequest request, HttpServletResponse response) {

		super(request, response);
	}

	@Override
	public void execute() throws InterruptedSectionException {

		HttpSession session = this.getRequest().getSession();

		/*
		 * SSOセッション無効
		 */
		String signonToken = this.getRequest().getParameter(SSOContextParameters.getInstance().getNamingOfSignonToken());
		String realm = this.getRequest().getParameter(SSOContextParameters.getInstance().getNamingOfRealm());
		String username = this.getRequest().getParameter(SSOContextParameters.getInstance().getNamingOfUsername());
		String password = this.getRequest().getParameter(SSOContextParameters.getInstance().getNamingOfPassword());

		/*
		 * SSOセッション無効 > サインオンシーケンス有効、かつ サインオン成功
		 *
		 * => リダイレクト : [コールバック]
		 * => パラメーター : [認証トークン]、[暗号化済み共通鍵]
		 */
		EnduserSignonSequence seq = (EnduserSignonSequence) session.getAttribute(signonToken);
		Serializable userObject = SSOProviderInitParameters
			.getInstance().getAuthenticator().auth(realm, username, password);

		if (seq != null && userObject != null) {

			SSOSymmetricCipher symCipher = new SSOSymmetricCipher();
			String authToken = this.newAuthorizationToken(
				SSOProviderInitParameters.getInstance().getSsoSessionStore());
			SSOSession sso = new SSOSession(authToken);
			sso.setCommonkey(symCipher.getCommonkeyAsHex());
			sso.setUserObject(userObject);

			SSOProviderInitParameters.getInstance().getSsoSessionStore().set(sso);
			session.setAttribute(SSOContextParameters.getInstance().getNamingOfAuthorizationToken(), authToken);

			SSOAsymmetricCipher cipher = new SSOAsymmetricCipher(seq.getPublickey());
			String encryptedCommonkey = cipher.encryptAsHex(sso.getCommonkey());

			NamedValuesUriBuilder b = new NamedValuesUriBuilder(seq.getCallback());
			b.append(SSOContextParameters.getInstance().getNamingOfAuthorizationToken(), authToken);
			b.append(SSOContextParameters.getInstance().getNamingOfEncryptedCommonkey(), encryptedCommonkey);

			this.sendRedirect(b.toString());
			throw new InterruptedSectionException(false);
		}
	}

	/**
	 * 認証トークンを生成します。
	 *
	 * @param store SSOセッションストア。
	 * @return 認証トークン。
	 */
	protected String newAuthorizationToken(SSOSessionStore store) {

		String token = null;

		while (token == null || store.exist(token)) {

			token = UUID.randomUUID().toString().replaceAll("-", "");
		}

		return token;
	}
}
